package com.jthinker.dao.impl;

import com.jthinker.bean.vo.QueryResult;
import com.jthinker.bean.vo.SearchFilter;
import com.jthinker.dao.BaseDao;
import com.jthinker.dao.UserDao;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * Created by chen.gang on 2015/2/14.
 */
@Repository
public class UserDaoImpl implements UserDao
{
    @Resource
    private BaseDao baseDao;

    @Override
    public boolean isUnique(String username)
    {
        String sql = "SELECT 1 FROM sys_user WHERE username=? LIMIT 1";
        return MapUtils.isEmpty(baseDao.read(sql, username));
    }

    @Override
    public void updatePass(String saltpass, Serializable id)
    {
        baseDao.update("UPDATE sys_user SET password=? WHERE id=?", saltpass, id);
    }

    @Override
    public void createUser(Map<String, Object> record)
    {
        baseDao.insert("sys_user", record);
    }

    @Override
    public Map<String, Object> findOne(Long userId)
    {
        return baseDao.read("SELECT * FROM sys_user WHERE id =?", userId);
    }

    @Override
    public Map<String, Object> findOneByUsername(String username)
    {
        return baseDao.read("SELECT * FROM sys_user WHERE username = ?", username);
    }

    @Override
    public QueryResult<Map<String, Object>> query(SearchFilter filter)
    {
        String sql = "SELECT id,username,role_ids,nickname FROM sys_user";
        Integer total = baseDao.queryTotal("sys_user", StringUtils.EMPTY);

        if (total == null || total.intValue() == 0)
        {
            return QueryResult.empty();
        }

        List<Map<String, Object>> list = baseDao.queryPagination2(sql, filter.getStart(), filter.getPageSize());

        return new QueryResult<Map<String, Object>>(total, list, filter.getPage(), filter.getPageSize());
    }

    @Override
    public Map<String, Object> login(String username, String saltPassword)
    {
        String sql = "SELECT * FROM sys_user WHERE username=? AND `password`=?";
        return baseDao.read(sql, username, saltPassword);
    }
}
